import http from 'wechat-http'
http.baseURL = 'https://live-api.itheima.net',
  // 添加拦截器
  http.intercept.request = (config) => {
    // 获取 app 实例
    // const app = getApp()
    // 得到 token
    // const token = app.token
    const token = wx.getStorageSync('token')
    // 自定义一个头部信息对象
    let defaultHeader = {}
    if (token) {
      defaultHeader.Authorization = token
    }
    // 将请求信息进行合并
    // config.header = Object.assign({}, defaultHeader, config.header)
    config.header = {
      ...defaultHeader,
      ...config.header
    }
    return config
  }


http.intercept.response = async ({ statusCode, data, config }) => {
  // console.log(res);
  if (statusCode === 401) {
    const refreshToken = wx.getStorageSync('refreshToken')
    // 判断请求的路径是否是 refreshToken 是：跳转到登录页；不是：继续执行
    if (config.url.includes('/refreshToken')) {
      const pages = getCurrentPages()
      const currentRoute = pages[pages.length - 1]
      const redirectURL = currentRoute.route
      // 跳转到登录页面
      return wx.redirectTo({ url: `/pages/login/index?redirectURL=/${redirectURL}` })
    }
    const res = await http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: 'Bearer ' + refreshToken
      }
    })
    console.log('res', res);
    // 保存新的token
    wx.setStorageSync('token', res.data.token)
    wx.setStorageSync('refreshToken', res.data.refreshToken)
    // 更新 Authorization
    res.config.header = Object.assign(...config.header, {
      Authorization: 'Bearer ' + res.data.token,
    })
    // 继续之前未完成的请求
    const result = await http({
      ...res.config
    })
    return result
  }
  // 将结果返回
  return data
}
// 挂载方法到全局
wx.http = http
// 模块导出
export default http